package com.ruoyi.yuwen.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.newAdd.returnResult.Data;
import com.ruoyi.common.newAdd.returnResult.Res;
import com.ruoyi.common.newAdd.utils.TimeUtil;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.yuwen.domain.Apply;
import com.ruoyi.yuwen.domain.Code;
import com.ruoyi.yuwen.domain.Settlement;
import com.ruoyi.yuwen.service.*;
import org.springframework.http.HttpRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.yuwen.domain.User;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 用户Controller
 * 
 * @author ruoyi
 * @date 2023-02-27
 */
@RestController
@RequestMapping("/yuwen/user")
public class UserController extends BaseController
{
    @Autowired
    private IUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ICodeService codeService;

    @Autowired
    private IApplyService applyService;

    @Autowired
    private IBillService billService;

    @Autowired
    private ISettlementService settlementService;

    /**
     * 查询用户列表
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(User user)
    {
        startPage();
        List<User> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 导出用户列表
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:export')")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, User user)
    {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 获取用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(userService.selectUserById(id));
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:add')")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody User user)
    {
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:edit')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody User user)
    {
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('yuwen:user:remove')")
    @Log(title = "用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userService.deleteUserByIds(ids));
    }

    /** 后台接口 **************************************************************************************************** */
    /** 后台接口 **************************************************************************************************** */
    /** 后台接口 **************************************************************************************************** */

    /**
     * 用户余额清零
     * @param userId
     * @return
     */
    @Transactional
    @GetMapping("/clearBalance")
    public AjaxResult clearBalance(@RequestParam("userId") Long userId)
    {
        User user = userService.selectUserById(userId);

        Settlement settlement = new Settlement();
        settlement.setUserId(user.getId());
        settlement.setUserName(user.getName());
        settlement.setAmount(user.getBalance());
        settlement.setAddtime(TimeUtil.getStringTime("yyyy-MM-dd HH:mm:ss"));
        settlementService.insertSettlement(settlement);

        billService.updateBillByUserId(userId);

        user.setBalance(0);
        return toAjax(userService.updateUser(user));
    }

    /** 前端接口 **************************************************************************************************** */
    /** 前端接口 **************************************************************************************************** */
    /** 前端接口 **************************************************************************************************** */


    //用户注册（需要验证验证码是否正确）
    @Transactional
    @GetMapping("/front/register")
    public Res register(@RequestParam("userName")String userName,
                     @RequestParam("phone")String phone,
                     @RequestParam("code")String code,
                     @RequestParam("password")String password,
                     @RequestParam("repeatPassword")String repeatPassword,
                     @RequestParam("fatherId")Long fatherId){

        User father = userService.selectUserById(fatherId);

        Code codeEntity = codeService.selectCodeByPhone(phone);
        if (null==codeEntity){
            return Res.error("请发送验证码！");
        }
        if (!codeEntity.getCode().equals(code)){
            return Res.error("验证码错误，请重新发送验证码！");
        }
        if (codeEntity.getAddTime()+600< TimeUtil.getTime()){
            return Res.error("验证码超时，请重新发送验证码！");
        }
        if (!password.equals(repeatPassword)){
            return Res.error("两次输入的密码不一致，请重新输入!");
        }

        User user = new User();
        user.setPhone(phone);
        List<User> list = userService.selectUserList(user);

        if (list.size()>0){
            return Res.error("该账号已存在，请更换账号名！");
        }
        user.setName(userName);
        user.setPassword(password);
        user.setBalance(0);
        user.setName(userName);
        user.setAddTime(TimeUtil.getStringTime("yyyy-MM-dd HH:mm:ss"));
        user.setFatherId(fatherId);
        user.setStock(0l);
        user.setActivateNum(0l);
        user.setUserLevel(103l);
        userService.insertUser(user);
        if (father.getUserLevel()==101l){
            Apply apply = new Apply();
            apply.setUserId(user.getId());
            apply.setUserName(user.getName());
            apply.setPhone(user.getPhone());
            apply.setState(0);
            apply.setAddtime(TimeUtil.getStringTime("yyyy-MM-dd HH:mm:ss"));
            applyService.insertApply(apply);
        }

        LoginUser loginUser = new LoginUser();
        SysUser sysUser = new SysUser();
        sysUser.setUserId(user.getId());
        sysUser.setUserName(user.getName());
        sysUser.setRoleId(user.getUserLevel());
        loginUser.setUser(sysUser);
        String token = tokenService.createToken(loginUser);

        codeService.deleteCodeById(codeEntity.getId());

        Data data = Data.ok().put("token",token).put("user",user);
        return Res.ok().put("data",data);
    }

    /**
     * 用户登陆
     * @param phone
     * @param password
     * @return
     */
    @GetMapping("/front/login")
    public Res login(@RequestParam("phone")String phone,
                     @RequestParam("password")String password){

        User user = new User();
        user.setPhone(phone);
        List<User> list = userService.selectUserList(user);
        if (list.size()<=0){
            return Res.error("该账号不存在，请检查账号是否正确！");
        }
        user = list.get(0);
        if (!user.getPassword().equals(password)){
            return Res.error("密码错误！");
        }
        LoginUser loginUser = new LoginUser();
        SysUser sysUser = new SysUser();
        sysUser.setUserId(user.getId());
        sysUser.setUserName(user.getName());
        sysUser.setRoleId(user.getUserLevel());
        loginUser.setUser(sysUser);
        String token = tokenService.createToken(loginUser);
        Data data = Data.ok().put("token",token).put("user",user);
        return Res.ok().put("data",data);
    }

    /**
     * 用户信息
     */
    @GetMapping("/front/userInfo")
    public Res userInfo(){
        Long userId = tokenService.getUserId();

        User user = userService.selectUserById(userId);

        return Res.ok().put("data", Data.ok().put("user",user));
    }

    /**
     * 上级用户信息
     */
    @GetMapping("/front/fatherInfo")
    public Res fatherInfo(){
        Long userId = tokenService.getUserId();
        User user = userService.selectUserById(userId);
        User father = userService.selectUserById(user.getFatherId());
        father.setPassword(null);
        father.setFatherId(null);
        father.setUserLevel(null);
        father.setBalance(null);
        father.setStock(null);

        return Res.ok().put("data", Data.ok().put("father",father));
    }

    /**
     * 修改密码
     * @param oldPassword
     * @param newPassword
     * @param repeatPassword
     * @return
     */
    @GetMapping("/front/changePassword")
    public Res changePassword(@RequestParam("oldPassword")String oldPassword,
                              @RequestParam("newPassword")String newPassword,
                              @RequestParam("repeatPassword")String repeatPassword){
        Long userId = tokenService.getUserId();
        System.out.println(userId);

        if (!newPassword.equals(repeatPassword)){
            return Res.errorShowMsg("两次输入的密码不一致，请重新输入!");
        }

        User user = userService.selectUserById(userId);

        System.out.println(user);

        if (!oldPassword.equals(user.getPassword())){
            return Res.errorShowMsg("密码错误!");
        }

        if (newPassword.equals(user.getPassword())){
            return Res.errorShowMsg("新密码和旧密码不能一致!");
        }

        user.setPassword(newPassword);
        userService.updateUser(user);

        return Res.okShowMsg("密码修改成功!");
    }

    /**
     * 忘记密码接口
     * @param phone
     * @param code
     * @param newPassword
     * @param repeatPassword
     * @return
     */
    @GetMapping("/front/forgetPassword")
    public Res changePassword(@RequestParam("phone")String phone,
                              @RequestParam("code")String code,
                              @RequestParam("newPassword")String newPassword,
                              @RequestParam("repeatPassword")String repeatPassword){

        if (!newPassword.equals(repeatPassword)){
            return Res.errorShowMsg("两次输入的密码不一致，请重新输入!");
        }

        Code codeEntity = codeService.selectCodeByPhone(phone);
        if (null==codeEntity){
            return Res.error("请发送验证码！");
        }

        if (!codeEntity.getCode().equals(code)){
            return Res.error("验证码错误，请重新发送验证码！");
        }

        if (codeEntity.getAddTime()+600< TimeUtil.getTime()){
            return Res.error("验证码超时，请重新发送验证码！");
        }

        User user = new User();
        user.setPhone(phone);
        List<User> list = userService.selectUserList(user);

        if (list.size()<=0){
            return Res.error("该账号不存在，请检查账号是否正确！");
        }

        user = list.get(0);
        user.setPassword(newPassword);
        userService.updateUser(user);

        codeService.deleteCodeById(codeEntity.getId());

        return Res.okShowMsg("密码修改成功!");
    }

    /**
     * 子级用户列表
     */
    @GetMapping("/front/childList")
    public Res childList(){
        Long userId = tokenService.getUserId();
        User user = new User();
        user.setFatherId(userId);

        List<User> list = userService.selectUserList(user);

        return Res.ok().put("data", Data.ok().put("total",new PageInfo(list).getTotal()).put("list",list));
    }
}
